package com.spring.demo.service;


import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.spring.demo.domain.User;
import com.spring.demo.domain.UserManager;
import com.spring.demo.page.PageCondition;
import com.spring.demo.repository.jpa.UserQueryRepository;

@Service
@Transactional(readOnly = true)
public class UserServiceServiceImpl extends BaseService<User, Long> implements UserService {

	@Autowired
	private UserQueryRepository userQueryRepository;
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public User save(User user) {
		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.setInstance(user);
		return userManager.save();
	}
	
	public User findByUserName(String userName) {
		return userQueryRepository.findByUserName(userName);
	}

	public User findByLoginName(String loginName) {
		return userQueryRepository.findByLoginName(loginName);
	}

	public Page<User> findAll(PageCondition pageCondition) {
		PageRequest pageRequest = new PageRequest(pageCondition.getPage(), pageCondition.getSize());
		Specification<User> specification = this.generateUserSpecification(pageCondition);
		return userQueryRepository.findAll(specification, pageRequest);
	}
	
	public Specification<User> generateUserSpecification(
			final PageCondition pageCondition) {
		Specification<User> specification = new Specification<User>() {
			public Predicate toPredicate(Root<User> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				
				return null;
			}
		};
		return specification;
	}
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public void deleteUser(Long id) {
		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.removeById(id);
	}
}
